package tools

import "sync"

type GenericsSyncMap[K any, V interface{}] struct {
	sync.Map
}

func NewGenericsSyncMap[K comparable, V interface{}]() *GenericsSyncMap[K, V] {
	return &GenericsSyncMap[K, V]{
		Map: sync.Map{},
	}
}

func (g *GenericsSyncMap[K, V]) Get(key K) (V, bool) {
	value, ok := g.Map.Load(key)
	if ok {
		return value.(V), true
	}
	var defaultValue V
	return defaultValue, false
}

func (g *GenericsSyncMap[K, V]) Put(key K, value V) {
	g.Map.Store(key, value)
}

func (g *GenericsSyncMap[K, V]) Delete(key K) {
	g.Map.Delete(key)
}

func (g *GenericsSyncMap[K, V]) Range(f func(key K, value V)) {
	g.Map.Range(func(key, val interface{}) bool {
		f(key.(K), val.(V))
		return true
	})
}

func (g *GenericsSyncMap[K, V]) Len() (len int) {
	g.Map.Range(func(key, val interface{}) bool {
		len++
		return true
	})
	return
}
